package com.fiidee.blog.controller;

import com.fiidee.blog.dto.BlogCategoryDTO;
import com.fiidee.blog.entity.Blog;
import com.fiidee.blog.entity.BlogCategory;
import com.fiidee.blog.entity.User;
import com.fiidee.blog.service.BlogCategoryService;
import com.fiidee.blog.service.BlogService;
import com.fiidee.blog.service.ConfigService;
import com.fiidee.blog.service.UserService;
import com.fiidee.blog.util.HtmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 界面相关的控制层
 * Created by 瑱彬 on 2015/5/26.
 */

@Controller
@RequestMapping("/")
public class ApplicationController {
    @Autowired
    BlogService blogService;

    @Autowired
    ConfigService configService;

    @Autowired
    UserService userService;

    @Autowired
    BlogCategoryService blogCategoryService;

    private ModelAndView getHtmlCommpont(ModelAndView andView) {
        List<Map<String, Object>> categorys = blogCategoryService.selectCategoryRightSide();
        andView.addObject("categorys", categorys);
        return andView;
    }

    private ModelAndView getMainModelAndView(String userId, String username, String name, String avatar) {
        ModelAndView andView = new ModelAndView();

        andView.addObject("username", username);
        andView.addObject("userId", userId);
        andView.addObject("name", name);
        andView.addObject("recommendUsers", userService.getRecommendUser());
        andView.addObject("recommendBlogs", blogService.getRecommendList());
        andView.addObject("avatar", avatar);
        andView = getHtmlCommpont(andView);
        return andView;
    }

    @RequestMapping("")
    public ModelAndView main(@CookieValue(value = "userId", defaultValue = "") String userId,
                             @CookieValue(value = "username", defaultValue = "") String username,
                             @CookieValue(value = "name", defaultValue = "") String name,
                             @CookieValue(value = "avatar", defaultValue = "") String avatar,
                             @RequestParam(value = "page", required = false, defaultValue = "1") String page, HttpServletRequest request, HttpServletResponse response) {
        int pageInt = Integer.parseInt(page);
        if (0 == pageInt) {
            pageInt = 1;
        }

        String pageNavigation = HtmlUtil.getPageHtml(pageInt, blogService.countHomeList(),
                configService.getNum("pageRows"), request.getContextPath() + "/", "page");


        ModelAndView andView = getMainModelAndView(userId, username, name, avatar);
        andView.addObject("list", blogService.getHomeList(pageInt));
        andView.addObject("pageNavigation", pageNavigation);
        andView.setViewName("main");
        return andView;
    }

    @RequestMapping("category")
    public ModelAndView category(@CookieValue(value = "userId", defaultValue = "") String userId,
                                 @CookieValue(value = "username", defaultValue = "") String username,
                                 @CookieValue(value = "name", defaultValue = "") String name,
                                 @CookieValue(value = "avatar", defaultValue = "") String avatar,
                                 @RequestParam(value = "page", required = false, defaultValue = "1") String page,
                                 String c, HttpServletRequest request, HttpServletResponse response) {

        int pageInt = Integer.parseInt(page);
        if (0 == pageInt) {
            pageInt = 1;
        }

        int catid = Integer.valueOf(c);

        String pageNavigation = HtmlUtil.getPageHtml(pageInt, blogService.countCategoryList(Integer.valueOf(c)),
                configService.getNum("pageRows"), request.getContextPath() + "/", "page");
        ModelAndView andView;
        andView = getMainModelAndView(userId, username, name, avatar);
        andView.addObject("list", blogService.getCategoryList(pageInt, catid));
        andView.addObject("pageNavigation", pageNavigation);
        andView.addObject("category", blogCategoryService.selectByPrimaryKey(catid));
        andView.setViewName("category");
        return andView;
    }

    @RequestMapping("home")
    public ModelAndView home(@CookieValue(value = "userId", defaultValue = "") String userId,
                             @CookieValue(value = "username", defaultValue = "") String username,
                             @CookieValue(value = "name", defaultValue = "") String name,
                             @CookieValue(value = "avatar", defaultValue = "") String avatar,
                             @RequestParam(value = "page", required = false, defaultValue = "1") String page,
                             HttpServletResponse response, HttpServletRequest request) {
        int id = 0;
        ModelAndView andView = new ModelAndView();
        try {
            id = Integer.valueOf(userId);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (id == 0) {
            try {
                response.sendRedirect("");
                return null;
            } catch (IOException e) {
                andView.setViewName("");
                return andView;
            }
        } else {
            int pageInt = Integer.parseInt(page);
            if (0 == pageInt) {
                pageInt = 1;
            }
            String pageNavigation = HtmlUtil.getPageHtml(pageInt, blogService.countUserList(id),
                    configService.getNum("pageRows"), request.getContextPath() + "/", "page");


            andView = getMainModelAndView(userId, username, name, avatar);
            andView.addObject("list", blogService.getSelfList(pageInt, id));
            andView.addObject("pageNavigation", pageNavigation);
            andView.addObject("user", userService.getUserInfo(id));
            andView.setViewName("home");
            return andView;
        }

    }

    @RequestMapping("userlist")
    public ModelAndView userlist(@CookieValue(value = "userId", defaultValue = "") String userId,
                                 @CookieValue(value = "username", defaultValue = "") String username,
                                 @CookieValue(value = "name", defaultValue = "") String name,
                                 @CookieValue(value = "avatar", defaultValue = "") String avatar,
                                 @RequestParam(value = "page", required = false, defaultValue = "1") String page,
                                 String u, HttpServletRequest request, HttpServletResponse response) {

        int pageInt = Integer.parseInt(page);
        if (0 == pageInt) {
            pageInt = 1;
        }

        int userid = Integer.valueOf(u);

        User user = userService.selectByPrimaryKey(userid);

        String pageNavigation = HtmlUtil.getPageHtml(pageInt, blogService.countUserList(Integer.valueOf(u)),
                configService.getNum("pageRows"), request.getContextPath() + "/", "page");
        ModelAndView andView = new ModelAndView();
        andView.addObject("list", blogService.getUserList(pageInt, userid));
        andView.addObject("username", username);
        andView.addObject("userId", userId);
        andView = getHtmlCommpont(andView);

        andView.addObject("author", user);
        andView.addObject("pageNavigation", pageNavigation);
        andView.setViewName("userlist");
        return andView;
    }


    @RequestMapping("login")
    public ModelAndView login() {
        ModelAndView andView = new ModelAndView();
        andView.setViewName("login");
        return andView;
    }

    @RequestMapping("register")
    public ModelAndView register() {
        ModelAndView andView = new ModelAndView();
        andView.setViewName("register");
        return andView;
    }

    @RequestMapping("publish")
    public ModelAndView publish(
            @CookieValue(value = "userId", defaultValue = "") String userId,
            @CookieValue(value = "username", defaultValue = "") String username,
            @CookieValue(value = "name", defaultValue = "") String name,
            @CookieValue(value = "avatar", defaultValue = "") String avatar,

            HttpServletRequest request, HttpServletResponse response) {
        int id = 0;
        ModelAndView andView = new ModelAndView();
        try {
            id = Integer.valueOf(userId);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (id == 0) {
            try {
                response.sendRedirect("");
                return null;
            } catch (IOException e) {
                andView.setViewName("");
                return andView;
            }
        }
        BlogCategoryDTO dto = new BlogCategoryDTO();
        dto.setStatement("ishow = 1");
        List<BlogCategory> categories = blogCategoryService.selectByDTO(dto);
        andView = getMainModelAndView(userId, username, name, avatar);
        andView.addObject("categories", categories);
        andView.setViewName("publish");
        return andView;
    }

    @RequestMapping("setting")
    public ModelAndView setting(
            @CookieValue(value = "userId", defaultValue = "") String userId,
            @CookieValue(value = "username", defaultValue = "") String username,
            @CookieValue(value = "name", defaultValue = "") String name,
            @CookieValue(value = "avatar", defaultValue = "") String avatar,
            HttpServletRequest request, HttpServletResponse response) {
        int id = 0;
        ModelAndView andView = new ModelAndView();
        try {
            id = Integer.valueOf(userId);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (id == 0) {
            try {
                response.sendRedirect("");
                return null;
            } catch (IOException e) {
                andView.setViewName("");
                return andView;
            }
        }
        andView = getMainModelAndView(userId, username, name, avatar);
        andView.addObject("user", userService.getUserInfo(id));
        andView.setViewName("setting");
        return andView;
    }

    private int countPlus(Integer blogId,int nowCount){
        Blog blogUpdate = new Blog();
        blogUpdate.setId(blogId);
        blogUpdate.setHits(nowCount + 1);
        return blogService.updateByPrimaryKeySelective(blogUpdate);
    }

    @RequestMapping("content")
    public ModelAndView content(
            @CookieValue(value = "userId", defaultValue = "") String userId,
            @CookieValue(value = "username", defaultValue = "") String username,
            @CookieValue(value = "name", defaultValue = "") String name,
            @CookieValue(value = "avatar", defaultValue = "") String avatar,
            int b, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView andView = new ModelAndView();
        Map<String, Object> blogContent = blogService.getBlogContent(b);
        if (blogContent == null || blogContent.isEmpty()) {
            andView.addObject("msg", "没有找到文章");
            andView.setViewName("common/error");
        } else {
            countPlus((Integer)blogContent.get("id"),(Integer)blogContent.get("hits"));

            andView = getMainModelAndView(userId, username, name, avatar);

            andView.addObject("blog", blogContent);
            andView.addObject("around", blogService.getArroundBlog(b));
            andView = getHtmlCommpont(andView);
            andView.setViewName("content");
        }
        return andView;
    }

    @RequestMapping("find")
    public ModelAndView find(
            @CookieValue(value = "userId", defaultValue = "") String userId,
            @CookieValue(value = "username", defaultValue = "") String username,
            HttpServletRequest request, HttpServletResponse response) {
        ModelAndView andView = new ModelAndView();
        andView.setViewName("find");
        return andView;
    }


}
